package com.jeesite.modules.kj.api.handler;

import com.jeesite.common.config.Global;
import com.jeesite.modules.common.exception.RequireLoginException;
import com.jeesite.modules.kj.api.enumCode.UnicomResponseEnums;
import com.jeesite.modules.kj.api.exception.UnicomRuntimeException;
import com.jeesite.modules.kj.api.vo.responseVo.ResponseBean;
import com.jeesite.modules.kj.exception.FreezMemberException;
import com.jeesite.modules.kj.exception.LowIntegralException;
import org.apache.ibatis.binding.BindingException;
import org.apache.shiro.dao.DataAccessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.ValidationException;
import java.net.ConnectException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

@RestControllerAdvice(annotations={RestController.class, Controller.class})
public class SpringExceptionHandler {


    private static final Logger logger = LoggerFactory.getLogger(SpringExceptionHandler.class);
    /**
     * 请求参数类型错误异常的捕获
     * @param e
     * @return
     */
    @ExceptionHandler(value={BindException.class})
    @ResponseBody
    @ResponseStatus(value= HttpStatus.BAD_REQUEST)
    public ResponseBean<String> badRequest(BindException e){
        logger.error("occurs error when execute method ,message {}",e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        boolean b = bindingResult.hasErrors();
        if (b){

            List<ObjectError> allErrors = bindingResult.getAllErrors();
            String error = "";
            for (ObjectError allError : allErrors) {
                error+= allError.getDefaultMessage()+",";
            }
            return new ResponseBean<>(Global.FALSE,"002",error);
        }else {
            return new ResponseBean<>(Global.FALSE, UnicomResponseEnums.BAD_REQUEST);
        }
    }

    /**
     * 404错误异常的捕获
     * @param e
     * @return
     */
    @ExceptionHandler(value={NoHandlerFoundException.class})
    @ResponseBody
    @ResponseStatus(value= HttpStatus.NOT_FOUND)
    public ResponseBean<String> badRequestNotFound(BindException e){
        logger.error("occurs error when execute method ,message {}",e);
        return new ResponseBean<>(Global.FALSE, null, UnicomResponseEnums.NOT_FOUND);
    }

    /**
     * mybatis未绑定异常
     * @param e
     * @return
     */
    @ExceptionHandler(BindingException.class)
    @ResponseBody
    @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseBean<String> mybatis(Exception e){
        logger.error("occurs error when execute method ,message {}",e);
        return new ResponseBean(Global.FALSE, UnicomResponseEnums.BOUND_STATEMENT_NOT_FOUNT);
    }
    /**
     * 自定义异常的捕获
     * 自定义抛出异常。统一的在这里捕获返回JSON格式的友好提示。
     * @param exception
     * @param request
     * @return
     */
    @ExceptionHandler(value={UnicomRuntimeException.class})
    @ResponseBody
    @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR)
    public <T> ResponseBean<T> sendError(UnicomRuntimeException exception, HttpServletRequest request){
        String requestURI = request.getRequestURI();
        logger.error("occurs error when execute url ={} ,message {}",requestURI,exception.getMessage());
        return new ResponseBean<>(Global.FALSE,exception.getCode(),exception.getMessage());
    }
    /**
     * 自定义异常的捕获
     * 自定义抛出异常。统一的在这里捕获返回JSON格式的友好提示。
     * @param exception
     * @param request
     * @return
     */
    @ExceptionHandler(value={RequireLoginException.class})
    @ResponseBody
    @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR)
    public <T> ResponseBean<T> sendError(RequireLoginException exception, HttpServletRequest request){
        String requestURI = request.getRequestURI();
        logger.error("occurs error when execute url ={} ,message {}",requestURI,exception.getMsg());
        return new ResponseBean<>(Global.FALSE, UnicomResponseEnums.MUST_LOGIN);
    }
    /**
     * 数据库操作出现异常
     * @param e
     * @return
     */
    @ExceptionHandler(value={SQLException.class, DataAccessException.class})
    @ResponseBody
    @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseBean<String> systemError(Exception e){
        logger.error("occurs error when execute method ,message {}",e);
        return new ResponseBean<>(Global.FALSE, UnicomResponseEnums.DATABASE_ERROR);
    }
    /**
     * 网络连接失败！
     * @param e
     * @return
     */
    @ExceptionHandler(value={ConnectException.class})
    @ResponseBody
    @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseBean<String> connect(Exception e){
        logger.error("occurs error when execute method ,message {}",e);
        return new ResponseBean<>(Global.FALSE, UnicomResponseEnums.CONNECTION_ERROR);
    }

    @ExceptionHandler(value={Exception.class})
    @ResponseBody
    @ResponseStatus(value= HttpStatus.METHOD_NOT_ALLOWED)
    public ResponseBean<String> notAllowed(Exception e){
        logger.error("occurs error when execute method ,message {}", e.getStackTrace());
        return new ResponseBean<>(Global.FALSE, UnicomResponseEnums.SYSTEM_ERROR);
    }
    @ExceptionHandler(value={LowIntegralException.class})
    @ResponseBody
    public ResponseBean<String> lowIntegralException(Exception e){
        logger.error("occurs error when execute method ,message {}",e);
        return new ResponseBean<>(Global.FALSE, "-32", e.getMessage());
    }

    @ExceptionHandler(value={ValidationException.class})
    @ResponseBody
    @ResponseStatus(value= HttpStatus.METHOD_NOT_ALLOWED)
    public ResponseBean<String> codeRepeat(Exception e){
        logger.error("occurs error when execute method ,message {}",e);
        return new ResponseBean<>(Global.FALSE, UnicomResponseEnums.BAD_REQUEST);
    }


    @ExceptionHandler(value={FreezMemberException.class})
    @ResponseBody
    @ResponseStatus(value= HttpStatus.METHOD_NOT_ALLOWED)
    public ResponseBean<String> freezeMember(Exception e){
        return new ResponseBean<>(Global.FALSE, "-018", e.getMessage());
    }

}
